package org.luxor.common.netty.protocol.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.luxor.common.netty.TcpNioClient;

import java.util.concurrent.TimeUnit;

/**
 * 客户端断开重连处理器
 *
 * @author Mr.yan @date 2023/12/4
 */
@ChannelHandler.Sharable
public class WatchdogClientHandler extends ChannelInboundHandlerAdapter {
    private final TcpNioClient tcpNioClient;

    public WatchdogClientHandler(TcpNioClient tcpNioClient) {
        this.tcpNioClient = tcpNioClient;
    }

    /**
     * 连接断开，自动重试
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        if (tcpNioClient != null && tcpNioClient.getClientOption().isReconnect()) {
            ctx.channel().eventLoop().schedule(tcpNioClient, 4, TimeUnit.SECONDS);
        }
        ctx.fireChannelInactive();
    }
}
